package com.aya.tb.context;

import com.aya.tb.CodeProcessor;
import com.aya.tb.RequestMap;
import com.aya.tb.annotation.ResponseBody;
import com.aya.tb.annotation.ResponseType;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

/**
 * 用责任链去匹配支持多种返回形式
 * <p>
 * 这里为了演示就直接在这里做了
 */
@Service
public class StandardResponseHandler implements ResponseHandler {
    /**
     * @param res
     * @param requestMap
     * @param ctx
     * @param container
     */
    @Override
    public void resolve(Object res, RequestMap requestMap, ChannelHandlerContext ctx, CodeProcessor container) throws IOException {
        ResponseBody annotation = requestMap.getMethod().getAnnotation(ResponseBody.class);
        boolean equals = ResponseType.SELF.equals(annotation.type());
        if (equals) {
            // 还要在增加一个序列化的服务去序列化 res
            System.out.println("server:" + res);

            byte[] bytes = res.toString().getBytes();
            ByteArrayOutputStream byteArrayInputStream = new ByteArrayOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(byteArrayInputStream);

            dataOutputStream.writeShort(container.code());
            dataOutputStream.write(bytes);
            ctx.channel().writeAndFlush(byteArrayInputStream.toByteArray());
        }
    }

}
